import { ref, onMounted } from 'vue';
const inBrowser = typeof window !== 'undefined';

const overflowScrollReg = /scroll|auto/i;
const defaultRoot = inBrowser ? window : undefined;

function isElement(node: any) {
	const ELEMENT_NODE_TYPE = 1;
	return node.tagName !== 'HTML' && node.tagName !== 'BODY' && node.nodeType === ELEMENT_NODE_TYPE;
}

export function getScrollParent(el: any, root = defaultRoot) {
	let node = el;

	while (node && node !== root && isElement(node)) {
		const { overflowY } = window.getComputedStyle(node);
		if (overflowScrollReg.test(overflowY)) {
			return node;
		}
		node = node.parentNode;
	}

	return root;
}

export default function useScrollParent(el: any, root: any) {
	const scrollParent = ref(null);
	console.log('checkPosition1111----00')
	onMounted(() => {
		console.log('checkPosition1111----1--00')
		const _el = el?.value || el;
		console.log('checkPosition1111----11', _el)
		if (_el) {
			scrollParent.value = getScrollParent(_el, root);
			console.log('checkPosition1111----2222', scrollParent.value)
		}
	});

	return scrollParent;
}
